package com.yunbiao.ybbusstopplate.serialport

import com.blankj.utilcode.util.LogUtils
import com.yunbiao.ybbusstopplate.utils.BytesUtils
import java.io.IOException
import java.io.InputStream

class ReadThread(inputStream:InputStream?,iSerialPortListener: ISerialPortListener?) : Thread() {

    var inputStream:InputStream?=inputStream
    var listener:ISerialPortListener?=iSerialPortListener

    override fun run() {
        super.run()
        while (!interrupted()){
            var size: Int
            try {
                val buffer = ByteArray(512)
                if (inputStream == null) {
                    LogUtils.d("inputStream--isnull")
                    return
                }
                size = inputStream!!.read(buffer)
                if (size > 0) {
                    val subByte = BytesUtils.SubByte(buffer, 0, size)
                    if (listener!=null){
                        listener?.onDataReceived(subByte, size)
                    }
                }
                try {
                    sleep(50) //延时50ms
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return
            }
        }
    }
}